import { getToken, removeToken, setToken } from '@/utils/auth'
import { isPlainObject } from '@guanwei/app-javascript'

const state = {
  token: getToken() || '',
  avatar: '',
  name: '',
  id: ''
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      const { username, password } = userInfo
      fakeLoginApi(username, password).then(response => {
        const token = response.data

        commit('SET_TOKEN', token)
        setToken(token)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },
  logout({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve(null)
    })
  },
  setUser({ commit }, payload) {
    if (!isPlainObject(payload)) return

    if ('name' in payload) {
      commit('SET_NAME', payload.name || '')
    }

    if ('avatar' in payload) {
      commit('SET_AVATAR', payload.avatar || '')
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

function fakeLoginApi(username, password) {
  return new Promise((r, j) => {
    setTimeout(() => {
      if (username === 'admin' && password === '1') {
        r({
          success: true,
          msg: '请求成功',
          code: 200,
          data: 'is-fake-token'
        })
      } else {
        j(new Error({
          success: false,
          code: 200,
          msg: '请求失败',
          data: ''
        }))
      }
    }, 800)
  })
}
